"""Timer module."""
from threading import Timer


class ScheduledTask:
    """
    Scheduled task execution.

    Run a task after a given interval.
    Allows rescheduling by calling start() multiple times.
    """

    def __init__(self, interval, function, *args, **kwargs):
        """
        Initialize scheduled task.

        Parameters:
        interval:   number of seconds to wait until the callback is executed.
        function:   callback function to call when the timer expires.
        args:       args for the callback call.
        kwargs:     kwargs for the callback call.
        """
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.timer = None

    def _callback(self):
        """Execute the callback function."""
        self.function(*self.args, **self.kwargs)

    def start(self):
        """
        Start the timer.

        If the timer was already started, the interval is restarted.
        """
        self.cancel()
        self.timer = Timer(self.interval, self._callback)
        self.timer.daemon = True
        self.timer.start()

    def cancel(self):
        """Cancel the timer."""
        if self.timer:
            self.timer.cancel()
